import dialogUtil from './dialogUtil'
import validateUtil from './validateUtil'
import storeUtil from './storeUtil'
import commonUtil from './commonUtil'
import qs from 'qs'
import dataHandle from '../config/dataHandle'
import config from '../config/config'
import { Loading } from 'element-ui'
import storage from '../tools/storage'
require('es6-promise').polyfill()
let options = {}
export default class httpUtil {

  static circle(key, value, result, comonData) {
    if (validateUtil.isArray(value)) {
      let tmpArray = new Array();
      for (let i = 0; i < value.length; i++) {
        let tmpValue = JSON.parse(JSON.stringify(value[i]));
        Object.keys(value[i]).forEach((tmpKey) => {
          httpUtil.circle(tmpKey, value[i][tmpKey], tmpValue, comonData);
        });
        tmpArray.push({
          ...tmpValue,
          ...comonData
        });
      }
      result[key] = tmpArray;
    } else if (validateUtil.isObject(value)) {
      let tmpValue = JSON.parse(JSON.stringify(value));
      Object.keys(value).forEach((tmpKey) => {
        httpUtil.circle(tmpKey, value[tmpKey], tmpValue, comonData);
      });
      result[key] = tmpValue;
    } else {
      result[key] = value;
    }
  }
  static handleData(data, comonData) {
    //统一设置加载loading状态,

    if (data && data.loading) {

      options.loadingInstance = Loading.service({
        fullscreen: true
      })


    }
    let result = {};
    if (validateUtil.isNull(data))
      return result;
    if (validateUtil.isNull(comonData))
      return data;
    result = {
      ...result,
      ...comonData
    };
    Object.keys(data).forEach((key) => {
      let value = data[key];
      httpUtil.circle(key, value, result, comonData);
    })
    return result;
  }
  // 返回数据基础处理
  static responseBaseHandle(res, func) {
    if (validateUtil.isNotNull(res) && res.status === 200 && validateUtil.isNotNull(res.data)) {
      const data = res.data
      //在响应完成之后关闭加载框
      if (options && options.loadingInstance) {

        options.loadingInstance.close()
      }
      switch (data.status) {
        case 0: // 系统内部状态
          if (validateUtil.isNotNull(data.msg)) {
            dialogUtil.successMsg(data.msg)
          } // 更改
          if (validateUtil.isNotNull(data.result)) { // 内容
            return func(data.result)
          } else { // 如果为空(则返回)
            return 'no content'
          }
          break
        case 1:
          if (validateUtil.isNotNull(data.msg)) {
            dialogUtil.errorMsg(data.msg)
          } else {

            dialogUtil.errorMsg('执行请求失败.')
          }
          break
        case 5:
          dialogUtil.errorMsg('用户鉴权失败.')
          storeUtil.removeAuthority()
          commonUtil.skipLogin()
          break
        case 9:
          if (validateUtil.isNotNull(data.msg)) {
            dialogUtil.errorMsg(data.msg)
          } else {
            dialogUtil.errorMsg('服务器异常.')
          }
          break
        case 10:
          if (validateUtil.isNotNull(data.msg)) {
            dialogUtil.errorMsg(data.msg)
          } else {
            dialogUtil.errorMsg('文件上传失败.')
          }
          
         
      }
      config.stateCode.forEach(item=>{
        if(data.status==item.code&&data.code!==10000){
          dialogUtil.errorMsg(item.message)
        }
      })
    }
  }

  static responseUnifyHandleByJson(res) {
    return this.responseBaseHandle(res, function (resl) {
      let result = resl
      if (validateUtil.isNotNull(result.pages) && validateUtil.isNotNull(result.total)) { // 分页
        if (validateUtil.isNotNull(result.list) && validateUtil.isArray(result.list)) { // 分页有内容
          result = dataHandle.handlePage(result)
        } else { // 无内容
          result.list = []
        }
      } else { // 列表或单条

        if (validateUtil.isArray(result)) { // 列表
          result = dataHandle.handleList(result)
        } else { // 单条查询
          result = dataHandle.handleSingle(result)
        }
      }
      return result
    })
  };

  static responseUnifyHandleByStatics(res) {
    return this.responseBaseHandle(res, function (result) {
      return result
    })
  };

  // 错误统一处理(不需要修改)
  static errorUnifyHandle(err) {
    if (err.message.includes('timeout')) {
      dialogUtil.errorMsg('请求超时')
    }
    if (err && err.response && err.response.status) {
      const response = err.response
      switch (response.status) {
        case 404:
          dialogUtil.errorMsg('请求地址出错.')
          break
        case 405:
          dialogUtil.errorMsg('请使用POST请求.')
          break
        case 408:
          dialogUtil.errorMsg('请求超时.')
          break
        case 500:
          dialogUtil.errorMsg('服务器内部错误.')
          break
        case 501:
          dialogUtil.errorMsg('服务未实现.')
          break
        case 502:
          dialogUtil.errorMsg('网关错误.')
          break
        case 503:
          dialogUtil.errorMsg('服务不可用.')
          break
        case 504:
          dialogUtil.errorMsg('网关超时.')
          break
        case 505:
          dialogUtil.errorMsg('HTTP版本不受支持.')
          break
        default:
          dialogUtil.errorMsg('服务其它错误.')
      }
      config.stateCode.forEach(item=>{
        if(data.status==item.status&&data.status!==10000){
          dialogUtil.errorMsg(item.message)
        }
      })
    }
    console.error(err)
    return err
  }

  // 请求统一处理(仅针对application/x-www-form-urlencoded格式)
  static requestUnifyHandle(axiosInstance) {
    axiosInstance.interceptors.request.use(
      config => {
        if (config.method == 'post' || config.method == 'get') {
          if (validateUtil.isNull(config.data)) {
            config.data = new Object()
          }
          const postdata = config.data
          config.data = qs.stringify(postdata)
        }
        return config
      },
      err => {
        return Promise.reject(err)
      }
    )
  };

  // 权限拦截处理
  static authorityUnifyHandle(axiosInstance) {
    const authorParam = storage.getCookie('token');
    if (validateUtil.isNull(authorParam)) {
      commonUtil.skipLogin()
    } else {
      axiosInstance.defaults.headers.post[config.constantConfig.userTokenConstant] = authorParam // 头验证
      // 增加各系统权限
      // if (validateUtil.isNotNull(authorParam.sysTypeId)) {
      //   axiosInstance.defaults.headers.post.sysTypeId = authorParam.sysTypeId
      // }
    }
  }

  // get权限处理
  static authorityUnifyHandleByGet(axiosInstance) {
    let authorParam = storeUtil.getAuthority();
    // if (validateUtil.isNull(authorParam) || validateUtil.isNull(authorParam[config.constantConfig.userTokenConstant]))
    //     commonUtil.skipLogin();
    // else {
    //     axiosInstance.defaults.headers.get[config.constantConfig.userTokenConstant] = authorParam[config.constantConfig.userTokenConstant];//头验证
    //     //增加各系统权限
    //     if(validateUtil.isNotNull(authorParam["sysTypeId"]))
    //         axiosInstance.defaults.headers.get["sysTypeId"] = authorParam["sysTypeId"];
    // }
  }

  static requestDataUnifyHandle(data) {
    return dataHandle.requestHandle(data)
  }
}